$(function() {
    //menu
    /*$('#privilege').accordion({
        active: $('.admin[value]:not([value=""])').parents("#info div").prev('h3'),
        change: function(event, ui) {
            $('.admin').removeAttr('value');
            $('.admininfo').remove();
            $( "#privilege" ).accordion( "resize" );
        }
    });
*/
    $('#tabs').tabs();
    //link or unlink
    var unlinked = $('#unlinked'), linked = $('#linked');
    $('#unlinked li:odd, #linked li:even').addClass('row1');
    $('#linked li:odd, #unlinked li:even').addClass('row0');

    //give search
    $('#unlinked_s,#linked_s').click(function(){
        var tmpthis = $(this);
        var tmpname = $(this).attr('id').split('_s')[0];
        var tmpshow = $(this).attr('alt');
        var source  = new Array(); 
        $('#' + tmpname + '> li').show().find('span').each(function(index){
            source[index]   = $(this).text();    
        });

        $(this).html('<input id="search" />');
        $("#search").autocomplete({
            source  : source,
            select  : function(event, ui){
                $('#' + tmpname).find('li').filter(function(){
                    return ($(this).find('span').text() == ui.item.value)?false:true;
                }).hide();
            }
        }).focus().blur(function(){
            tmpthis.html('<span>'+tmpshow+'</span>');
        });
        
    });
    
    //give draggable
    $('li',$('.user2group')).draggable({
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: $( "#usertogroup" ).length ? "#usertogroup" : "document", // stick to demo-frame if present
        helper: "clone",
        cursor: "move"
    });

    $('li',$('.group2user')).draggable({
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: $( "#grouptouser" ).length ? "#grouptouser" : "document", // stick to demo-frame if present
        helper: "clone",
        cursor: "move"
    });

    unlinked.droppable({
        accept: "#linked > li",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            deleteli(ui.draggable, unlinked);
        }
    });

    linked.droppable({
        accept: "#unlinked > li",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            deleteli(ui.draggable, linked);
        }
    });

    function deleteli (item, ulelement) {
        item.fadeOut(function(){
            item.prependTo(ulelement).fadeIn(function(){
                $.ajax({
                    type:'POST',
                    url:'/websvn/privilege.php',
                    dataType:"html",
                    data:{name2     : ulelement.attr('name'),
                          name      : item.find('span').text(),
                          type      : ulelement.attr('id'),
                          option    : item.parents('table').attr('id')
                    },
                    success: function(html){
                        $('#footer').after(html);
                        $('#unlinked li:odd, #linked li:even').removeClass().addClass('row1 ui-draggable');
                        $('#linked li:odd, #unlinked li:even').removeClass().addClass('row0 ui-draggable');
                    }
                });
            });
        });
    }

    //checkbox
    $('.writable input').click(function() {
        var level   = $(this).attr('level');
        var belong  = $(this).attr('belong');
        var path    = $(this).attr('path');
        var dispath = new Array();
        if (level == 0) {
            $('.writable input[level!=0]:checked').removeAttr('checked');
        } else {
            $('.writable input:checked').filter(function(index){
                var Tbelong = $(this).attr('belong');
                var Tlevel  = $(this).attr('level');
                return ( (Tbelong.substr(0, belong.length) == belong && Tlevel > level ) || (belong.substr(0, Tbelong.length) == Tbelong && Tlevel < level ) );    
            }).removeAttr('checked').each(function(index){
                dispath[index] = $(this).attr('path');
            });
        }
        var auth;   
        var writable = $(this).attr('checked');
        var readable = $(this).parent().parent().find('.readable input').attr('checked');
        if (writable && readable) {
            auth = 3;
        } else if (writable && !readable) {
            auth = 2;
        } else if (!writable && readable) {
            auth = 1;
        } else auth =0;

        $.ajax({
            type:'POST',
            url:'/websvn/privilege.php',
            dataType:"html",
            data:{path      : path,
                  username  : $('#usermanage').val(),
                  groupname : $('#groupmanage').val(),
                  auth      : auth,
                  dispath   : dispath,
                  level     : level,
                  repo      : $('#repname option:selected').val(),
                  type      : 'w'
                  },
            success: function(html){
                $('#footer').after(html);
            }
        });
    });
    $('.readable input').click(function() {
        var level   = $(this).attr('level');
        var belong  = $(this).attr('belong');
        var path    = $(this).attr('path');
        var dispath = new Array();
        if (level == 0) {
            $('.readable input[level!=0]:checked').removeAttr('checked');
        } else {
            $('.readable input:checked').filter(function(index){
                var Tbelong = $(this).attr('belong');
                var Tlevel  = $(this).attr('level');
                return (( Tbelong.substr(0, belong.length) == belong && Tlevel > level ) || (belong.substr(0, Tbelong.length) == Tbelong && Tlevel < level ) );    
            }).removeAttr('checked').each(function(index){
                dispath[index] = $(this).attr('path');
            });
        }
        var auth;   
        var readable = $(this).attr('checked');
        var writable = $(this).parent().parent().find('.writable input').attr('checked');
        if (writable && readable) {
            auth = 3;
        } else if (writable && !readable) {
            auth = 2;
        } else if (!writable && readable) {
            auth = 1;
        } else auth =0;

        $.ajax({
            type:'POST',
            url:'/websvn/privilege.php',
            dataType:"html",
            data:{path      : path,
                  username  : $('#usermanage').val(),
                  groupname : $('#groupmanage').val(),
                  auth      : auth,
                  dispath   : dispath,
                  level     : level,
                  repo      : $('#repname option:selected').val(),
                  type      : 'r'
                  },
            success: function(html){
                $('#footer').after(html);
            }
        });
    });
    //valid_date
    $(".vdate:has(span:not(.nodefined))").click(function(){
        var tmpspan = $(this).html();
        var path    = $(this).next().find('input').attr('path');
        $(this).find('span').replaceWith('<input id="vdate" />');
        $( "#vdate" ).datepicker({
            dateFormat: "yy-mm-dd",
            hideIfNoPrevNext: true,
            minDate: new Date(),
            onClose: function(){
                $("#vdate").replaceWith(tmpspan);
            },
            onSelect: function(dateText, inst){
                $("#vdate").replaceWith('<span>'+dateText+'</span>');
                $.ajax({
                    type:'POST',
                    url:'/websvn/privilege.php',
                    dataType:"html",
                    data:{
                        path      : path,
                        username  : $('#usermanage').val(),
                        groupname : $('#groupmanage').val(),
                        vdate     : dateText,
                        repo      : $('#repname option:selected').val(),
                        type      : 'vdate'
                    },
                    success: function(html){
                        $('#footer').after(html);
                    }
                });
            }
        }).focus();
    });
    //useradd
    $('#passwd').blur(function(){
        if($(this).val().length != 0) $('#comfirm').removeAttr('disabled').focus();
    }).click(function(){
        $('#comfirm').removeAttr('value').attr('disabled',true).next('span').remove();
        $(this).removeAttr('value');
        $('#submitB').attr('disabled', true);
    });
    $('#comfirm').blur(function(){
        if($(this).val() != $('#passwd').val()) {
            $(this).after('<span class="ui-icon ui-icon-closethick"></span>').attr('disabled',true);
        } else if($(this).val().length != 0 && $(this).val() == $('#passwd').val()){
            $(this).after('<span class="ui-icon ui-icon-check"></span>').attr('disabled',true);
            $('#submitB').removeAttr('disabled');
        } 
    });
    $('#desc').blur(function(){
        if($(this).val().length != 0 ) $('#submitB').removeAttr('disabled');
        else $('#submitB').attr('disabled',true);
    });
    $('#submitB').click(function(){
        $.ajax({
            type:'POST',
            url:'/websvn/privilege.php',
            dataType:"html",
            data:{
                username  : $('#useradd').val(),
                groupname : $('#groupadd').val(),
                password  : ($('#passwd').val())?$('#passwd').val():'',
                isadmin   : $('#isadmin').attr('checked')?255:0,
                reponame  : $('#repoadd').val(),
                desc      : $('#desc').val(),
                type      : 'add'
            },
            success: function(html){
                $('#submitB').val("Success!");
                $("form:first").submit();        
            }
        });
    });
    $('#dialog').dialog({
        autoOpen    : false,
        buttons: { 
            "Ok"    : function() {
                $.ajax({
                    type:'POST',
                    url:'/websvn/privilege.php',
                    dataType:"html",
                    data:{
                        username  : $('#useradd').val(),
                        reponame  : $('#repoadd').val(),
                        groupname  : $('#groupadd').val(),
                        type      : 'del'
                    },
                    success: function(html){
                        $('#deleteB').val("Success!");
                        $("form:first").submit();        
                    }
                });
                $(this).dialog("close"); 
            },
            "Cancel": function() {
                $(this).dialog("close"); 
            }},
            modal:true,
            resizable:false,
            dialogClass:"ui-state-error"
    });
    $('#deleteB').click(function(){
        $('#dialog').dialog('open');
    });
    
});
